/*
 * @Author: your name
 * @Date: 2021-08-24 12:39:06
 * @LastEditTime: 2021-11-02 17:43:33
 * @LastEditors: Please set LastEditors
 * @Description: In User Settings Edit
 * @FilePath: \macc.admin.vue\src\projectCommon\store\modules\group\index.js
 */
/**
 * 分支Group bar
 * 分组有网络和设备类型 有些业务下只能选择设备 不可以选择分组  每个路由页面需要配置下类型
 *  this.$store.commit('Group/SET_GROUP_TYPE', 'ALL'); 默认是所有组
 *  this.$store.commit('Group/SET_GROUP_TYPE', 'LOCATION');  不可以选择分组  只能是网络
 * 分组变化后端会通知前端
 */

import {
  maccApi,
  requestHttp,
  groupTree2Map,
  totalProject,
} from '@utils/index';

const state = {
  groupInfo: null, //当前选择分组的信息
  groupId: parseInt(sessionStorage.getItem('maccGroupId')) || 0, //默认分组ID
  groupTree: null, //所有分组菜单
  groupType: 'ALL', //根据业务设置 默认为ALL。业务不能选择分组是设置为LOCATION
  grouproot: null,
  groupMap: {},
  isExperienceNet: false, //是否是体验项目
  isExperiencScene: null, //体验项目的场景类型
  shared: 0,
  accepted: 0,
};
const mutations = {
  SET_GROUPID(state, payload) {
    let isChange = false;
    if (state.groupId != payload) {
      isChange = true;
    }
    state.groupId = payload;
    sessionStorage.setItem('maccGroupId', payload);
    if (state.groupMap && state.groupMap[payload]) {
      state.groupInfo = state.groupMap[payload];
      sessionStorage.setItem(
        'currentGroupInfo',
        JSON.stringify(state.groupInfo)
      );
      //更新旧框架的groupBar
      if (window != window.top && isChange) {
        window.top.groupBar.setCurrentGroup(state.groupInfo);
        window.top.groupBar.updateGroupInfo();
      }
    }
  },
  SET_GROUP_TREE(state, payload) {
    state.groupTree = payload;
    // sessionStorage.setItem('groupInfo', JSON.stringify(payload)); //旧框架使用，存整个分组信息(新旧框架同域，公用一个sessionStorage)
  },
  SET_GROUP_TYPE(state, payload) {
    state.groupType = payload;
  },
  SET_GROUPROOT(state, payload) {
    state.grouproot = payload;
    // storage.set('grouproot', JSON.stringify(payload));
  },
  SET_GROUPMAP(state, payload) {
    console.log('**************SET_GROUPMAP', payload);
    state.groupMap = { ...payload };
    // storage.set('grouproot', JSON.stringify(payload));
  },
  SET_FLAG_EXPERIENCE_NET(state, payload) {
    state.isExperienceNet = payload.simulation;
    if (payload.simulation) {
      state.isExperiencScene = payload.scene;
    }
  },
  SET_SHARED(state, payload) {
    state.shared = payload;
  },
  SET_ACCEPTED(state, payload) {
    state.accepted = payload;
  },
  // //将第一个网络设置选中
  // SET_FIRST_BUILDING_GROUP(state) {
  //   const { groupMap } = state;
  //   const firstBuidingGroup = Object.values(groupMap)
  //     .reverse()
  //     .find((item) => {
  //       return item.type == 'BUILDING';
  //     });
  //   if (!firstBuidingGroup) return;
  //   const { groupId } = firstBuidingGroup;

  //   // state.groupInfo = null;
  // },
};

const actions = {
  //获取用户分组树
  getGroupTree({ commit }) {
    return new Promise((resolve, reject) => {
      var data = {
        api: maccApi.GET_GROUP_TREE,
        method: 'GET',
      };
      requestHttp(data)
        .then((res) => {
          if (res && res.code == 0) {
            let groupMap = {};
            groupTree2Map(res.groups, null, groupMap);
            const totalcount = totalProject(groupMap);
            //dispatch('User/setProject', totalcount,{root:true});
            commit('User/SET_PROJECT', totalcount, { root: true });
            commit('SET_GROUPMAP', groupMap);
            commit('SET_GROUP_TREE', res.groups);
            commit('SET_GROUPROOT', getRootGroup(res.groups));
            resolve();
          } else {
            reject(res);
          }
        })
        .catch((error) => {
          reject(error);
        });
    });
  },
  updataGroupTree({ dispatch }) {
    dispatch('getGroupTree');
    if (self != parent) {
      window.parent.postMessage(
        { module: 'VUE_GROUPCHANGE' },
        window.location.origin
      );
    }
  },

  //设置第一个网络组为选中分组
  setFirstBuildingGroup({ state, commit }) {
    const { groupMap } = state;
    const firstBuidingGroup = Object.values(groupMap)
      .reverse()
      .find((item) => {
        return item.type == 'BUILDING';
      });
    if (!firstBuidingGroup) return;
    const { groupId } = firstBuidingGroup;
    commit('SET_GROUPID', groupId);
  },
};
const getters = {};

const getRootGroup = function (group) {
  if (group.subGroups && group.subGroups.length > 0) {
    return {
      groupId: group.subGroups[0].groupId,
      name: group.subGroups[0].name,
    };
  } else {
    return { groupId: '', name: '' };
  }
};

export default {
  namespaced: true, //开启命名空间，更好的区分使用stage,防止不同stage模块中的方法重名
  state,
  getters,
  mutations,
  actions,
};
